import React, { useEffect, useMemo, useRef, useState } from 'react'
import { useNavigate } from 'react-router-dom';
import { Button, Input, NavBar,Toast } from 'antd-mobile'
import styles from './css/message.module.css'

const MessagePage = () => {
    const nav = useNavigate()
    const chatEl=useRef(null)
    const [msgVal,setMsgVal]=useState("")
    const [chatList,setChatList]=useState([])

    const user_id=1;
    const server_id=8877;


    // 聊天地址
    const ws=useMemo(()=>{
      return new WebSocket(
        `ws:124.221.74.149:8003/koa/ws?user_id=${user_id}&server_id=${server_id}`
      )
    },[])


    //websocket断联后怎么重新建立连接
    useEffect(()=>{
     ws.onopen=()=>{
        console.log("链接成功");
        ws.send(JSON.stringify({type: "getChatList"}))
     }
    },[])


    useEffect(()=>{
      ws.onmessage=(msg)=>{
         const {type,data}=JSON.parse(msg.data)
          if(type === "getChatList"){
             setChatList(data)
          }else if(type === "addMessage"){
             setChatList((pre)=>[...pre,data])
          }
      }
    },[])


    // 对话页考虑新消息接收过来滚动沉底
    useEffect(()=>{
      if(chatEl.current){
         console.log(11);
         chatEl.current.scrollTop= 10000
      }
    },[chatList])


    // 判断
    const handel=()=>{
        if(!msgVal) return Toast.show("请输入聊天内容")
         ws.send(
          JSON.stringify({
             type: "addMessage",
              data:{
                user_id,
                server_id,
                message: msgVal
              }
          })
        )
        setMsgVal("")
    }
    
  return (
    <div className={styles.meWrpa}>
      {/*布局*/}
      <NavBar onBack={() => nav(-1)}>消息聊天</NavBar>
      <main ref={chatEl}>
       <div className={styles.chatList}>
        {chatList.map((item,ind)=>{
            const ClassItem =
             item.dir === 1 ? "chat-item-right" : "chatList-item-left"
            const dirAvarat =
             item.dir === 1 ? item.user_avarat : item.server_avarat
             return (
                <div key={ind} className={styles[ClassItem]}>
                 <div>
                  <img className={styles.Avarat} src={dirAvarat} alt='' />
                 </div>
                 <div>
                   <div className={styles.text}>{item.message}</div>
                   <div className={styles.image}></div>
                   <div className={styles.video}></div>
                 </div>
                </div>
             )
        })}
       </div>
      </main>
      <footer>
        <Input 
         placeholder='请输入内容'
         onChange={(val)=>{
            setMsgVal(val)
         }}
        />
        <Button onClick={()=>handel()}>发送</Button>
      </footer>
    </div>
  )
}

export default MessagePage
